package com.citywithincity.db.meta;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.codehaus.jackson.annotate.JsonIgnore;

import com.citywithincity.interfaces.IDestroyable;

/**
 * 表结构
 * @author renxueliang
 *
 */
public class TableStruct implements IDestroyable {
	/**
	 * 表名称
	 */
	private String name;
	/**
	 * 注释
	 */
	private String comment;
	/**
	 * 
	 */
	@JsonIgnore
	private Map<String, ColumnStruct> columnMap;
	/**
	 * 主键
	 */
	@JsonIgnore
	private ColumnStruct[] pks;
	
	public TableStruct(List<ColumnStruct> columns, String name, String comment){
		//按字段名称排序
		columnMap = new TreeMap<String, ColumnStruct>();
		
		//初始化字段列表
		List<ColumnStruct> structs = new ArrayList<ColumnStruct>(2);
		for (ColumnStruct columnStruct : columns) {
			if(columnStruct==null){
				throw new RuntimeException("culumn is null");
			}
			columnMap.put(columnStruct.getName().toUpperCase(), columnStruct);
			if(columnStruct.getKeyType() == KeyType.Primary){
				structs.add(columnStruct);
			}
		}
		pks = new ColumnStruct[structs.size()];
		structs.toArray(pks);
		
		//其他至
		this.name = name;
		this.comment = comment;
	}
	
	
	
	/**
	 * 获取所有字段
	 * @return
	 */
	public Collection<ColumnStruct> getColumns(){
		return columnMap.values();
	}
	
	/**
	 * 按字段名称获取字段
	 * @param name
	 * @return
	 */
	public ColumnStruct getColumn(String name){
		return columnMap.get(name.toUpperCase());
	}
	

	public ColumnStruct[] getPks(){
		return pks;
	}

	public String getComment() {
		return comment;
	}


	public String getName() {
		return name;
	}



	@Override
	public void destroy() {
		
	}



	public Map<String,Object> toJson() {
		Map<String,Object> data = new HashMap<String, Object>();
		data.put("name", name);
		data.put("comment", comment);
		data.put("columns", getColumns());
		return data;
	}



	

	
	
	
}
